<?php

namespace app\admin\controller\fa;

use app\common\controller\Backend;
use app\common\job\ImportChapterZip;
use app\common\logic\comic\ComicLogic;
use app\common\model\fa\comic\ChapterSource;
use think\Db;
use think\Queue;
use think\Validate;

/**
 * 章节管理
 *
 * @icon fa fa-circle-o
 */
class Chapter extends Backend
{

    /**
     * Chapter模型对象
     * @var \app\admin\model\fa\Chapter
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\fa\Chapter;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['comic'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'title', 'is_vip', 'thumb', 'intro', 'created_at', 'updated_at']);
                $row->visible(['comic']);
                $row->getRelation('comic')->visible(['title']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function resource($ids)
    {
        $chapterSourceModel = new ChapterSource();
        if ($this->request->isGet()) {
            $resource = $chapterSourceModel->where('chapter_id', $ids)->select();
            $images = '';
            if ($resource) {
                $images = join(',', array_map(function ($item) {
                    return $item['source'];
                }, $resource));
            }
            return $this->view->assign('images', $images)->assign('ids', $ids)->fetch();
        } else {
            try {
                Db::startTrans();
                $validate = new Validate(
                    array(
                        'resource' => ['require']
                    ),
                    array(
                        'resource.require' => '请上传图片'
                    ),
                );
                $body = $this->request->post('row/a');
                if (!$validate->check($body)) {
                    throw new \Exception($validate->getError());
                }
                $resource = explode(',', $body['resource']);
                if ($resource) {
                    $insert = [];
                    foreach ($resource as $item) {
                        $insert[] = [
                            'chapter_id' => $ids,
                            'source' => $item,
                        ];
                    }
                    $chapterSourceModel->where('chapter_id', $ids)->delete();
                    if (!$chapterSourceModel->insertAll($insert)) {
                        throw new \Exception('添加失败');
                    }
                }
                Db::commit();
            } catch (\Throwable $exception) {
                Db::rollback();
                $this->error($exception->getMessage());
            }
            $this->success('添加成功');
        }
    }

    public function zip($comic_id)
    {
        if ($this->request->isAjax()) {
            $zipPath = $this->request->post('row.zip');
            if (!$zipPath) {
                $this->error('请上传压缩包');
            }
            Queue::push(ImportChapterZip::class, [
                'path' => public_path($zipPath),
                'comic_id' => $comic_id,
            ]);
            $this->success('已放入后台导入');
        }
        return $this->view->assign('comic_id', $comic_id)->fetch();
    }
}
